package edu.ustb.struts2.hibernate;

import java.util.Date;
import java.util.UUID;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import edu.ustb.struts2.bean.School;
import edu.ustb.struts2.bean.UserBean;


public class TestHibernate {
	
	public static void main(String[] args) {
		addSchool();
	}
	
	public static void addSchool() {
		School school = new School();
//		school.setId(UUID.randomUUID().toString());
		school.setName("计算机与通信工程学院");
		school.setCreateTime(new Date());
		school.setStudentNum(1000);
		school.setRemark("博学厚德 求实创新");
		
		Configuration config = new Configuration().configure();
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
		SessionFactory factory = config.buildSessionFactory(sr);
		Session session = factory.openSession();
		Transaction tran = null;
		try {
			tran = session.beginTransaction();
			session.save(school);
			tran.commit();
		} catch (Exception e) {
			if (tran!=null) {
				tran.rollback();
			}
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	public static void addUser() {
		UserBean user = new UserBean();
		user.setId(UUID.randomUUID().toString());
		user.setName("zpc");
		user.setAge(24);
		user.setRemark("备注");
		user.setSchool(6);
		user.setSex("男");
		user.setStuNo("S20111179");

		Configuration config = new Configuration().configure();
		ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
		SessionFactory factory = config.buildSessionFactory(serviceRegistry);
		
		Session session = factory.openSession();
		Transaction tran = null;
		try {
			tran = session.beginTransaction();
			session.save(user);
			tran.commit();
		} catch (Exception e) {
			if (tran!=null) {
				tran.rollback();
			}
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

}
